//
//  LinePreDetailVC.m
//  ImGuider
//
//  Created by llt on 2017/9/13.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "LinePreDetailVC.h"
#import "TagView.h"
#import "StarRateView.h"
#import "WPYNavBar.h"
#import "Transition.h"
#import "ProgressBtn.h"

#import "LinePreTab1Cell.h"
#import "LinePreTab2Cell.h"

#import "GuiderDetailVC.h"
#import "UserCommentsVC.h"
#import "UserSubmitQustionVC.h"
#import "IGShare.h"
#import "CityTourPlay.h"
#import "ScenicPlayVC.h"

#import "HomeAdAlertVCViewController.h"
#import "PaymentPageVC.h"
#import "AllRecordPointVC.h"
@interface LinePreDetailVC () <UITableViewDataSource, UITableViewDelegate, WPYNavBarDelegate, PlayerManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIImageView *lineImagaeView;
@property (weak, nonatomic) IBOutlet UILabel *lineNameLabel;
@property (weak, nonatomic) IBOutlet TagView *tagView;
@property (weak, nonatomic) IBOutlet StarRateView *rateView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *spotCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *listenMinsLabel;
@property (weak, nonatomic) IBOutlet UILabel *listenCountLabel;

@property (weak, nonatomic) IBOutlet ProgressBtn *playBtn;
@property (weak, nonatomic) IBOutlet UILabel *tryListenLabel;
@property (weak, nonatomic) IBOutlet UIButton *openScenicBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineImageViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineImageViewTop;


@property (nonatomic, strong) WPYNavBar *sectionView;

@property (nonatomic, strong) LineModel *lineModel;

@property (nonatomic) BOOL isDrag;

@property (nonatomic, strong) UserSubmitQuestionCell *currentCell;
@property (nonatomic, strong) Question *cquestion;

@end

@implementation LinePreDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tryListenLabel.text = MYLocalizedString(@"PUBLIC_PLAY_TRIALS", nil);
    
    [self.openScenicBtn setTitle:MYLocalizedString(@"CITYTOUR_LISTEN", nil) forState:UIControlStateNormal];
    
    [self rightBarButtonWithImageName:@"分享" selector:@selector(showShareSheet:)];
    [self setNavGradient];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAudioState:) name:kPlayManagerState object:nil];
    
    self.barBGAlpha = 0;
    self.playBtn.space = 0.f;
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.sectionHeaderHeight = 60;
    self.lineImageViewHeight.constant = SCREEN_WIDTH * 9.0f / 16;
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:kBGColor];
    [self loadDataBlock:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    if ([PlayerManager shareManeger].isPlay) {
        [[PlayerManager shareManeger] stop];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.NoAnimation = NO;
}

- (void)loadDataBlock:(void(^)(void))block {
    
    @weakify(self);
    [NetAPIManager getLineDetailWithLinID:self.lineid block:^(LineModel *model, NSError *error) {
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.lineModel = model;
        [self setupData];
        if (block) {
            block();
        }
    }];
}

- (void)setupData {
    
    [self.lineImagaeView setImageURL:[NSURL URLWithString:self.lineModel.pictures] placeholderImage:[UIImage imageNamed:@"placeholder_rec"]];
    self.lineNameLabel.text = self.lineModel.linename;
    self.tagView.tagsArray = self.lineModel.tagArray;
    [self.rateView setScore:self.lineModel.score.floatValue / 10.0];
    self.rateView.canRating = NO;
    
    
    
    if (self.lineModel.bought && [UserManager sharedManager].user.role.integerValue != UserRolesTypeAdmin && self.lineModel.pricelevel.integerValue != 0) {
        
        self.priceLabel.text = MYLocalizedString(@"SITEPLAY_PURCHASED", nil);
    } else {
        
        self.priceLabel.text = self.lineModel.price;
    }
    
    self.spotCountLabel.text = self.lineModel.recordcount;
    
    self.listenMinsLabel.text = [NSString stringWithFormat:@"%@mins",self.lineModel.timelabel];
    self.listenCountLabel.text = self.lineModel.visits;
    [self.tableView reloadData];

    if (self.sectionView.LabelArray.count == 3) {
        UILabel *label2 = self.sectionView.LabelArray[1];
        
        label2.text = [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_COMMENT", nil), self.lineModel.commentnum.intValue];
        
        UILabel *label3 = self.sectionView.LabelArray[2];
        
        label3.text = [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_QUESTION", nil), self.lineModel.questionnum.intValue];
    }
}

- (WPYNavBar *)sectionView {
    
    if (!_sectionView) {
        _sectionView  = [[WPYNavBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,60) titleColor:kTitleColor andSelectTitleColor:kThemeColor];
        _sectionView.titleColor = kContentColor;
        _sectionView.titleFont = Font(14);
        _sectionView.delegate = self;
        
        [_sectionView AddNavBarArray:@[MYLocalizedString(@"LINEDETAIL_SECTION_DETAIL", nil),
                                       [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_COMMENT", nil), self.lineModel.commentnum.intValue],
                                       [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_QUESTION", nil), self.lineModel.questionnum.intValue]] isBtnLine:YES btnLineColor:kThemeColor];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(16, 59, SCREEN_WIDTH - 32, 1)];
        lineView.backgroundColor = kBGColor;
        [_sectionView addSubview:lineView];
    }
    
    return _sectionView;
}

- (void)showShareSheet:(UIButton *)sender {
    
    [self popSheet];
}

// 送优惠券
- (void)showHomeAd {
    
    if (![AppManager sharedManager].version.info.coupon || ![[[AppManager sharedManager].language lowercaseString] hasPrefix:@"zh-hans"]) {
        
        return;
    }
    
    if ([UserManager sharedManager].token.length != 0) {
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasAlertAd"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    BOOL hasAlertAd = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasAlertAd"];
    
    if (!hasAlertAd) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            HomeAdAlertVCViewController *alertVC = [HomeAdAlertVCViewController new];
            alertVC.delegate = self;
            [alertVC showWithVC:self];
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasAlertAd"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        });
    }
}

- (void)changeAudioState:(NSNotification *)notif {
    
    NSInteger state = [notif.userInfo[kPlayManagerState] integerValue];
    NSString  *url = notif.userInfo[kCurrentPlayURL];

    if (![url isEqualToString:self.cquestion.answer] && ![url isEqualToString:self.lineModel.playpath]) {
        return;
    }

    switch (state) {
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        {
            if ([url isEqualToString:self.cquestion.answer]) {
               
                [self.currentCell stopPlay];
                self.cquestion = nil;
                self.currentCell = nil;
                
            } else if([self.lineModel.playpath isEqualToString:[PlayerManager shareManeger].currentURL]) {

                self.playBtn.selected = NO;
                [self.playBtn setProgress:0.f];
            }
        }
            break;
    }
    
}


- (IBAction)tryPlay:(UIButton *)sender {
    
    if (self.cquestion) {
        
        [self.currentCell stopPlay];
        self.cquestion = nil;
        self.currentCell = nil;
        
    }
    
    if (self.playBtn.selected || !self.lineModel) {
        
        [[PlayerManager shareManeger] pause];
        
        [MobClick event:@"3_0_1"];
        return;
    }
    [MobClick event:@"3_0_2"];
    [PlayerManager shareManeger].delegate = self;
    
    if (![AppManager sharedManager].allowWhenPlay && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
        
        [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_COMMIT", nil) commit:^{
            [AppManager sharedManager].allowWhenPlay = YES;
            if (![[PlayerManager shareManeger].currentURL isEqualToString:self.lineModel.playpath]) {
                [[PlayerManager shareManeger] playMusic:self.lineModel.playpath withIsPlay:YES];
                
            }else{
                [[PlayerManager shareManeger] play];
            }
            
            self.playBtn.selected = YES;
            
        } cancel:nil];
        
        return;
    }
    
    if (![[PlayerManager shareManeger].currentURL isEqualToString:self.lineModel.playpath]) {
        [[PlayerManager shareManeger] playMusic:self.lineModel.playpath withIsPlay:YES];
    }else{
        [[PlayerManager shareManeger] play];
    }
    self.playBtn.selected = YES;
}


- (void)updateProgressWith:(CGFloat)value {

    if (![self.cquestion.answer isEqualToString:[PlayerManager shareManeger].currentURL]) {
        [self.playBtn setProgress:value];
    }

}

- (IBAction)openTheLine:(UIButton *)sender {
    
    if (![UserManager sharedManager].token) {
        
        [self loginAction];
        return;
    }
    
    if (!self.lineModel.bought) {
        
        PaymentPageVC * paymentVC = [[PaymentPageVC alloc] init];
        paymentVC.lineModel = self.lineModel;
        paymentVC.delegate = self;
        
        BaseNavigationController * nav = [[BaseNavigationController alloc] initWithRootViewController:paymentVC];
        [self presentViewController:nav animated:YES completion:nil];
        
        return;
    }
    
    [self choosePageVCWithAlert:NO];
}

- (void)loginAction {
    
    LoginVC *loginVC = [LoginVC new];
    loginVC.delegate = self;
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
}


- (void)choosePageVCWithAlert:(BOOL) alert {
    
    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    
    
    if (self.lineModel.type.integerValue == 1) {
        
        for (UIViewController *vc in marr) {
            if ([vc isKindOfClass:[CityTourPlay class]]) {
                [marr removeObject:vc];
                break;
            }
        }
        self.navigationController.viewControllers = marr;
        
        CityTourPlay * vc= [[CityTourPlay alloc] init];
        vc.pageType = 2;
        vc.lineModel = self.lineModel;
        self.NoAnimation = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        
        
        for (UIViewController *vc in marr) {
            if ([vc isKindOfClass:[ScenicPlayVC class]]) {
                [marr removeObject:vc];
                break;
            }
        }
        self.navigationController.viewControllers = marr;
        
        ScenicPlayVC *playVC = [[ScenicPlayVC alloc] init];
        playVC.alert = alert;
        [AppManager sharedManager].lineid = self.lineid;
        playVC.lineModel = self.lineModel;
        
        playVC.pageType = 2;
        self.NoAnimation = YES;
        [self.navigationController pushViewController:playVC animated:YES];
    }
}


- (void)paySuccessCallback {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    [self loadDataBlock:^{
        
        if (self.lineModel.bought) {
            [self choosePageVCWithAlert:YES];
        }
    }];
}

- (void)loginSuccessCallback {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    [self loadDataBlock:nil];
}


#pragma mark -UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.lineModel ? 3 : 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == 0) {
        LinePreTab1Cell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"tab1"];
        cell1.linemodel = self.lineModel;
        cell1.delegate = self;
        return cell1;
    }
    
    LinePreTab2Cell *cell = [tableView dequeueReusableCellWithIdentifier:indexPath.row == 1 ? @"tab2":@"tab3"];
    cell.type = indexPath.row;
    cell.linemodel = self.lineModel;
    cell.delegate = self;
    cell.superVC = self;
    
    return cell;
}

#pragma mark -UITableViewDelegate

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    return self.sectionView;
}

#pragma mark -UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat header = self.headView.frame.size.height - kNavigationBarHeight - 8;//这个header其实是section的header到导航栏的距离
    CGFloat distance = scrollView.contentOffset.y;
    
    self.title = @"";
    
    if (distance <= header && distance >= 0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-distance, 0, 0, 0);
        
        self.barBGAlpha = distance / header;
        
    } else if (distance > header) {
        
        scrollView.contentInset = UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0);
        
        self.barBGAlpha = 1;
        self.title = self.lineModel.linename;
    } else {
        
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.barBGAlpha = 0;
        
        self.lineImageViewTop.constant = distance;
        self.lineImageViewHeight.constant = SCREEN_WIDTH * 9 / 16 - distance;
    }
    
    if (!self.isDrag) {
        return;
    }
    
    CGRect rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    if (distance < (CGRectGetMaxY(rect) - kNavigationBarHeight - 60) - 8) {
        
        self.sectionView.selectIndex = 0;
    } else {
        
        rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        
        if (distance < (CGRectGetMaxY(rect) - kNavigationBarHeight - 60) - 8) {
            
            self.sectionView.selectIndex = 1;
        } else {
            
            self.sectionView.selectIndex = 2;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    self.isDrag = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.isDrag = NO;
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    self.isDrag = YES;
    
    [scrollView setContentOffset:CGPointZero animated:YES];
    return NO;
}


#pragma mark -webinterface

- (void)jumpAllPoint{
    
    AllRecordPointVC * vc = [AllRecordPointVC new];
    
    vc.lineModel = self.lineModel;
    self.NoAnimation = YES;
    [self.navigationController pushViewController:vc animated:YES];

}
- (void)jumpguider {
    
    GuiderDetailVC * vc = [GuiderDetailVC new];
    vc.guiderID = self.lineModel.guideid;
    
    self.NoAnimation = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)jumpcomment {
    
    UserCommentsVC * commentsVC = [[UserCommentsVC alloc] init];
    commentsVC.lineID = self.lineModel.lineid;
    
    self.NoAnimation = YES;
    [self.navigationController pushViewController:commentsVC animated:YES];
}

- (void)jumpquestion {
    
    UserSubmitQustionVC * vc = [[UserSubmitQustionVC alloc] init];
    
    vc.lineModel = self.lineModel;
    self.NoAnimation = YES;
    [self.navigationController pushViewController:vc animated:YES];
}



#pragma mark - UserSubmitQuestionCellDelegate

- (void)answerAudioTapped:(UserSubmitQuestionCell *)cell question:(Question *)question {
    
    if ([question.qid isEqualToString:self.cquestion.qid]) {
        [[PlayerManager shareManeger] pause];
        return;
    }
    
    if ([[PlayerManager shareManeger].currentURL isEqualToString:question.answer]) {
        [[PlayerManager shareManeger] play];
    } else {
        
        if ([[PlayerManager shareManeger].currentURL isEqualToString:self.cquestion.answer]) {
            [self.currentCell stopPlay];
        }
        
        [[PlayerManager shareManeger] playAnswerVideoWith:question.answer];
    }
    
    [NetAPIManager clickCountWithID:question.qid type:@(3).stringValue];
    self.currentCell = cell;
    self.cquestion = question;
    [cell startPlay];
}

#pragma  mark - WPYNavBarDelegate
-(void)selectChangetoViewNum:(NSInteger)num {
    
    [self.tableView setContentInset:UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0)];
    
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:num inSection:0];
    self.isDrag = NO;
//    
    [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
    // _navOperation = operation;
    
    if (self.NoAnimation) {
        
        return nil;
    }
    
    return [Transition transitionWithTransitionType:operation == UINavigationControllerOperationPush ? PageCoverTransitionPush:PageCoverTransitionPop];
}

#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    @weakify(self)
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    NSString * descrbe = self.lineModel.type.integerValue == 1 ? MYLocalizedString(@"SHARE_LINE_MESSAGE", nil):MYLocalizedString(@"SHARE_SCENIC_MESSAGE", nil);
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        @strongify(self);
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:[NSString stringWithFormat:@"fxh5customline/%@",self.lineid] title:self.lineModel.linename descr:descrbe thumImage:self.lineModel.pictures object:self.lineModel.playpath type:2 completion:nil];
    };
    [self.sl_popupController dismiss];
}


@end
